package online.longzipeng.householdbillssystem.common.utils;

import lombok.extern.slf4j.Slf4j;
import online.longzipeng.householdbillssystem.common.exception.AppException;
import org.apache.ibatis.annotations.Delete;
import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @Author: lzp
 * @Date: 2021/2/10 13:54
 * 自定义md5加密
 */
@Slf4j
public class Md5Utils {

    private static MessageDigest md5;
    private static BASE64Encoder base64Encoder;

    static {
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        base64Encoder = new BASE64Encoder();
    }

    /**
     * md5加密密码
     * @param password
     * @return
     */
    public static String encrypt(String password){
        String newPassword = "";
        try {
            newPassword = base64Encoder.encode(md5.digest(password.getBytes("utf-8")));
        } catch (UnsupportedEncodingException e) {
            if (log.isDebugEnabled()) {
                log.warn(String.format("密码加密失败！！密码为：%s",password));
            }
            throw new AppException();
        }
        return newPassword;
    }

    /**
     * 验证密码是否与加密后的密码一致
     * @return
     */
    public static boolean checkPassword(String password,String md5Password){
        return md5Password.equals(encrypt(password));
    }
}
